package com.xuhuan.juc.ticket;

import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author huan.xu
 * @Date 2021/12/28 11:13
 * @Description 题目：三个售票员 卖出 30张票
 * 线程   操作  资源类
 */
public class SaleTicketDemo {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.saleTicket();
            }
        }, "线程1").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.saleTicket();
            }
        }, "线程2").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.saleTicket();
            }
        }, "线程3").start();
    }
}

/**
 * 票
 */
@Slf4j
class Ticket {
    private int number = 30;
    private Lock lock = new ReentrantLock();

    public synchronized void saleTicket() {
        lock.lock();
        try {
            if (number > 0) {
                log.info("线程[{}]，卖出了第[{}]张票，还剩下[{}]张票", Thread.currentThread().getName(), number--, number);
            }
        } finally {
            lock.unlock();
        }
    }
}
